﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WroxGallery.Actions;
using WroxGallery.Models;
using WroxGallery.Models.Interfaces;

namespace WroxGallery.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        private IConfigurationRepository _configurationRepository;
        private IGalleryRepository _galleryRepository;

        public HomeController(IConfigurationRepository configurationRepository,
            IGalleryRepository galleryRepository)
        {
            _configurationRepository = configurationRepository;
            _galleryRepository = galleryRepository;
        }

        [TitleFilter("Home")]
        public ActionResult Index()
        {
            PhotoCollection photos = _galleryRepository.GetLatestPhoto(5);
            ViewData["AlbumName"] = "Recent pics";
            return View(photos);
        }

        [TitleFilter("About")]
        public ActionResult About()
        {
            ViewData["AboutText"] = _configurationRepository.About;

            return View();
        }

        [TitleFilter("Album")]
        public ActionResult Album(string Id, string albumName)
        {
            PhotoCollection photos = _galleryRepository.GetPhotosInAlbum(Id, 5);
            ViewData["AlbumName"] = "Album " + albumName;
            ViewData["Title"] = albumName;
            return View("Index", photos);
        }


        public ActionResult Search(string search)
        {
            return RedirectToAction("Tag", new { Id = search });
        }

        [TitleFilter("Tag")]
        public ActionResult Tag(string Id)
        {
            PhotoCollection photos = _galleryRepository.SearchPhotosByTag(Id, 5);

            ViewData["AlbumName"] = "Search result: " + Id;
            ViewData["Title"] = Id;
            return View("Index", photos);
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewResult result = filterContext.Result as ViewResult;
            if (result != null)
            {
                result.ViewData["Albums"] = _galleryRepository.GetAlbums(5);
            }
        }

        public ActionResult Tags(string q)
        {
            StringCollection tags = _galleryRepository.TagList(q);
            StringBuilder builder = new StringBuilder();
            foreach (var s in tags)
            {
                builder.AppendLine(s);
            }
            string tagList = builder.ToString();
            tagList = tagList.TrimEnd('\r', '\n');
            return Content(tagList);
        }
    }
}
